<template>
  <div class="container" @click="closeEmojiPicker">
    <!-- <div class="chat-header">
      <h2>deepSeek AI 助手</h2>
    </div> -->

    <div class="chat-messages" ref="messagesContainer">
      <div
        v-for="(message, index) in messages"
        :key="index"
        :class="['message-item', message.role]"
      >
        <div class="avatar">
          <img v-if="message.role === 'assistant'" :src="girl" alt="AI" />
          <img v-else :src="boy" alt="User" />
        </div>
        <div class="message-content">
          <div class="sender-name" v-if="message.role === 'assistant'">
            AI助手
          </div>
          <div class="sender-name" v-if="message.role === 'user'">我</div>
          <div class="message-bubble">
            <TextComponent :textInfo="message.content"></TextComponent>
            <div v-if="message.role === 'assistant'" class="message-actions">
              <el-tooltip content="重新生成" placement="top">
                <el-icon :size="16" color="#999">
                  <Refresh @click="regenerateAnswer(message, index)" />
                </el-icon>
              </el-tooltip>
              <el-tooltip content="复制" placement="top">
                <el-icon :size="16" color="#999">
                  <DocumentCopy @click="copyMessage(message.content)" />
                </el-icon>
              </el-tooltip>
              <div class="divider"></div>
              <el-tooltip content="满意" placement="top">
                <el-icon :size="16" color="#999">
                  <CircleCheck @click="yesornoMassage('满意')" />
                </el-icon>
              </el-tooltip>
              <el-tooltip content="不满意" placement="top">
                <el-icon :size="16" color="#999">
                  <CircleClose @click="yesornoMassage('不满意')" />
                </el-icon>
              </el-tooltip>
            </div>
          </div>
        </div>
      </div>
      <!-- </div> -->
    </div>

    <div class="chat-input-container">
      <div class="emoji-container-wrapper" v-show="showEmojiPicker">
        <div class="emoji-container" @click.stop>
          <div class="emoji-content">
            <div
              v-for="emoji in emojiCategories[currentEmojiTab].emojis"
              :key="emoji"
              class="emoji-item"
              @click="insertEmoji(emoji)"
            >
              {{ emoji }}
            </div>
          </div>

          <div class="emoji-tabs">
            <div
              v-for="(category, index) in emojiCategories"
              :key="index"
              :class="['emoji-tab', { active: currentEmojiTab === index }]"
              @click="currentEmojiTab = index"
            >
              {{ category.icon }}
            </div>
          </div>
        </div>
      </div>

      <div class="input-toolbar">
        <div class="toolbar-btn" @click.stop="toggleEmojiPicker">
          <i class="emoji-icon">😊</i>
        </div>
        <div class="toolbar-btn" @click.stop="changeModel">
          <el-icon><Switch /></el-icon>
        </div>
        <!-- 这里可以添加更多功能按钮 -->
        <div class="toolbar-placeholder"></div>
      </div>

      <div class="input-wrapper">
        <el-input
          v-model="inputMessage"
          type="textarea"
          :rows="4"
          :autosize="{ minRows: 4, maxRows: 8 }"
          placeholder="输入您的问题..."
          resize="none"
          @keyup.enter="sendMessage"
          @click.stop
          :disabled="isThinking"
        />
        <el-button
          type="primary"
          icon="Position"
          class="send-button"
          v-if="!isThinking"
          @click="sendMessage"
          >发送</el-button
        >
        <el-button
          type="primary"
          icon="Position"
          class="cancel-button"
          v-else
          @click="cancelMessage"
          >取消</el-button
        >
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, nextTick, onMounted, onUnmounted } from "vue";
import { useSetting } from "@/store/setting";
import { ElMessage } from "element-plus";
import boy from "@/assets/images/boy.webp";
import TextComponent from "../../components/TextComponent/index.vue";
import girl from "@/assets/images/girl.webp";
// 引入流式请求
import { sendStreamRequest } from "@/utils/streamParser";
const userStore = useSetting();

const currentEmojiTab = ref(0);
const showEmojiPicker = ref(false);
const messages = ref([
  {
    role: "assistant",
    content: "你好！我是AI助手，很高兴为您服务。请问有什么我可以帮助您的吗？",
  },
]);
// 表情分类
const emojiCategories = ref([
  {
    icon: "😊",
    name: "表情",
    emojis: [
      "😀",
      "😃",
      "😄",
      "😁",
      "😆",
      "😅",
      "😂",
      "🤣",
      "😊",
      "😇",
      "🙂",
      "🙃",
      "😉",
      "😌",
      "😍",
      "🥰",
      "😘",
      "😗",
      "😙",
      "😚",
      "😋",
      "😛",
      "😝",
      "😜",
      "🤪",
      "🤨",
      "🧐",
      "🤓",
      "😎",
      "🤩",
    ],
  },
  {
    icon: "👍",
    name: "手势",
    emojis: [
      "👍",
      "👎",
      "👊",
      "✊",
      "🤛",
      "🤜",
      "🤞",
      "✌️",
      "🤟",
      "🤘",
      "👌",
      "👈",
      "👉",
      "👆",
      "👇",
      "☝️",
      "✋",
      "🤚",
      "🖐",
      "🖖",
    ],
  },
  {
    icon: "❤️",
    name: "符号",
    emojis: [
      "❤️",
      "🧡",
      "💛",
      "💚",
      "💙",
      "💜",
      "🖤",
      "💔",
      "❣️",
      "💕",
      "💞",
      "💓",
      "💗",
      "💖",
      "💘",
      "💝",
      "💟",
      "☮️",
      "✝️",
      "☪️",
    ],
  },
  {
    icon: "🐱",
    name: "动物",
    emojis: [
      "🐶",
      "🐱",
      "🐭",
      "🐹",
      "🐰",
      "🦊",
      "🐻",
      "🐼",
      "🐨",
      "🐯",
      "🦁",
      "🐮",
      "🐷",
      "🐸",
      "🐵",
      "🙈",
      "🙉",
      "🙊",
      "🐒",
      "🐔",
    ],
  },
  {
    icon: "🍎",
    name: "食物",
    emojis: [
      "🍎",
      "🍐",
      "🍊",
      "🍋",
      "🍌",
      "🍉",
      "🍇",
      "🍓",
      "🍈",
      "🍒",
      "🍑",
      "🥭",
      "🍍",
      "🥥",
      "🥝",
      "🍅",
      "🍆",
      "🥑",
      "🥦",
      "🥬",
    ],
  },
]);

// 切换表情选择器显示
const toggleEmojiPicker = () => {
  showEmojiPicker.value = !showEmojiPicker.value;
};

// 关闭表情选择器
const closeEmojiPicker = () => {
  if (showEmojiPicker.value) {
    showEmojiPicker.value = false;
  }
};

// 插入表情
const insertEmoji = (emoji) => {
  inputMessage.value += emoji;
  showEmojiPicker.value = false;
};
//切换模型
const changeModel = () => {
  currentModel.value = currentModel.value === "qwen" ? "deepseek" : "qwen";
  userStore.changeModel(currentModel.value);

  ElMessage.success(
    "模型切换成功,当前模型为" +
      (currentModel.value == "qwen" ? "通义千问" : "deepseek")
  );
};
const inputMessage = ref("");
const messagesContainer = ref(null);
const isThinking = ref(false);
const currentAbortController = ref(null); // 用于存储当前的 AbortController
const isScrolling = ref(false);

// 添加模型选择相关的状态
const currentModel = ref("qwen");

// 添加模型配置
const modelConfig = {
  qwen: {
    url: "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",
    apiKey: "sk-e7d33f45344c4fe6a7a59cb062fb6f90",
    model: "qwq-32b",
  },
  deepseek: {
    url: "https://api.deepseek.com/chat/completions",
    apiKey: "sk-1630d0d4b1fa43ab9a3691ae566dbcfe",
    model: "deepseek-chat",
  },
};

// 优化后的滚动函数
const scrollToBottom = async (smooth = true) => {
  if (isScrolling.value) return;

  try {
    isScrolling.value = true;

    // 等待 DOM 更新
    await nextTick();

    if (!messagesContainer.value) return;

    const container = messagesContainer.value;
    const scrollHeight = container.scrollHeight;

    // 使用平滑滚动
    container.scrollTo({
      top: scrollHeight,
      behavior: smooth ? "smooth" : "auto",
    });
  } finally {
    // 确保状态被重置
    setTimeout(() => {
      isScrolling.value = false;
    }, 100);
  }
};

// 监听消息变化
watch(
  messages,
  async (newMessages, oldMessages) => {
    // 只有在新增消息时才滚动
    if (newMessages.length > oldMessages.length) {
      await scrollToBottom();
    }
  },
  { deep: true }
);

// 监听消息内容变化（用于流式响应）
watch(
  () => messages.value.map((m) => m.content),
  async () => {
    // 检查是否在底部附近
    if (messagesContainer.value) {
      const container = messagesContainer.value;
      const isNearBottom =
        container.scrollHeight - container.scrollTop - container.clientHeight <
        100;

      if (isNearBottom) {
        await scrollToBottom();
      }
    }
  },
  { deep: true }
);

const sendMessage = async () => {
  if (!inputMessage.value.trim() || isThinking.value) return;

  const userMessage = inputMessage.value;
  messages.value.push({
    role: "user",
    content: userMessage,
  });
  inputMessage.value = "";

  isThinking.value = true;

  const controller = new AbortController();
  currentAbortController.value = controller;

  try {
    let params = {
      messages: [
        ...messages.value.map((msg) => ({
          role: msg.role || "assistant",
          content: msg.content,
        })),
      ],
    };

    messages.value.push({ content: "", role: "assistant" });
    const aiMessageIndex = messages.value.length - 1;
    const regex = "/---s*###.*?###s*---/g";

    // 根据当前选择的模型发送请求
    const config = modelConfig[currentModel.value];
    await sendStreamRequest({
      url: config.url,
      data: {
        model: config.model,
        messages: params.messages,
        stream: true,
      },
      apiKey: config.apiKey,
      onData: async (content) => {
        // const cleanedText = content.replace(regex, "").trim();
        messages.value[aiMessageIndex].content += content;
      },
      signal: controller.signal,
    });
  } catch (error) {
    if (error.name !== "AbortError") {
      // 如果不是手动取消的错误
      console.error("发送失败:", error);
      ElMessage.error("获取回复失败，请重试");
    } else {
      ElMessage.info("请求已取消");
      // 可能需要将最后一条用户消息标记为失败或移除
    }
  } finally {
    isThinking.value = false;
    currentAbortController.value = null;
    currentAbortController.value = null; // 清理 AbortController
    scrollToBottom();
  }
};

// 复制消息内容
const copyMessage = (content) => {
  navigator.clipboard
    .writeText(content)
    .then(() => {
      ElMessage.success("复制成功");
    })
    .catch(() => {
      ElMessage.error("复制失败");
    });
};

// 获取上一条用户消息
const getLastUserMessage = (currentIndex) => {
  for (let i = currentIndex - 1; i >= 0; i--) {
    if (messages.value[i].role === "user") {
      return messages.value[i].content;
    }
  }
  return null;
};
// 修改重新生成函数
const regenerateAnswer = async (currentMessage, index) => {
  if (isThinking.value) return;

  // 获取上一条用户消息
  const userMessage = getLastUserMessage(index);
  if (!userMessage) {
    ElMessage.warning("未找到相关问题");
    return;
  }

  // 删除当前的 AI 回答
  messages.value.splice(index, 1);
  isThinking.value = true;

  // 创建新的 AbortController
  const controller = new AbortController();
  currentAbortController.value = controller;

  try {
    // 准备请求参数
    let params = {
      model: "qwen-plus",
      messages: [
        ...messages.value.map((msg) => ({
          role: msg.role || "assistant",
          content: msg.content,
        })),
      ],
      stream: true,
    };

    // 添加一个空的 AI 回复消息，用于实时更新
    messages.value.push({ content: "", role: "assistant" });

    // 获取最新消息的索引
    const aiMessageIndex = messages.value.length - 1;

    // 发送流式请求
    const config = modelConfig[currentModel.value];
    await sendStreamRequest({
      url: config.url,
      data: {
        model: config.model,
        messages: params.messages,
        stream: true,
      },
      apiKey: config.apiKey,
      onData: async (content) => {
        // 清理特殊字符
        // const regex = /---\s*###.*?###\s*---/g;
        // const cleanedText = content.replace(regex, "").trim();
        messages.value[aiMessageIndex].content += content;
      },
      signal: controller.signal,
    });

    // 滚动到底部
    scrollToBottom();
  } catch (error) {
    if (error.name !== "AbortError") {
      console.error("重新生成失败:", error);
      ElMessage.error("重新生成失败，请重试");
      // 恢复原来的回答
      messages.value.splice(index, 0, currentMessage);
    } else {
      ElMessage.info("重新生成已取消");
      // 移除最后一条未完成的消息
      messages.value.pop();
    }
  } finally {
    isThinking.value = false;
    currentAbortController.value = null;
    scrollToBottom();
  }
};

// 取消消息
const cancelMessage = () => {
  if (currentAbortController.value) {
    currentAbortController.value.abort(); // 发出中止信号
    console.log("尝试取消请求...");
    // isThinking 状态会在 finally 块中被设置为 false
  }
};
const yesornoMassage = (val) => {
  if (val === "满意") {
    ElMessage.success("谢谢您的满意");
  } else {
    ElMessage.error("感谢您的反馈,已收到");
  }
};
onMounted(() => {
  scrollToBottom(false);
  window.addEventListener("resize", () => scrollToBottom(false));
});
onUnmounted(() => {
  window.removeEventListener("resize", () => scrollToBottom(false));
});
</script>

<style scoped lang="scss">
// 统一滚动条样式
@mixin custom-scrollbar {
  &::-webkit-scrollbar {
    width: 6px;
    height: 6px;
  }

  &::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 3px;
  }

  &::-webkit-scrollbar-thumb {
    background: #c0c4cc;
    border-radius: 3px;
  }

  &::-webkit-scrollbar-thumb:hover {
    background: #909399;
  }
}

.container {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  background-color: #e4e7ed;
  padding-top: 30px;
}

.chat-header {
  padding: 5px 20px;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #f5f7fa;

  h2 {
    margin: 0;
    font-size: 18px;
    color: #303133;
  }
}
.chat-messages {
  flex: 1;
  padding: 60px;
  overflow-y: auto;
  box-sizing: border-box;
  scroll-behavior: smooth; // 添加平滑滚动
  -webkit-overflow-scrolling: touch; // 改善移动端滚动体验
  background: url("@/assets/images/bg1.jpg") repeat center center;

  // 优化滚动条样式
  &::-webkit-scrollbar {
    width: 6px;
  }

  &::-webkit-scrollbar-track {
    background: #f1f1f1;
  }

  &::-webkit-scrollbar-thumb {
    background: #888;
    border-radius: 3px;

    &:hover {
      background: #555;
    }
  }

  // 确保内容不会被底部输入框遮挡
  padding-bottom: 50px;
  .message-item {
    display: flex;
    margin-bottom: 10px;

    &.user {
      flex-direction: row-reverse;

      .message-content {
        align-items: flex-end;

        .message-bubble {
          background-color: #ebf5ff;
          color: #333;
          border-radius: 10px 2px 10px 10px;
          box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
        }
      }
    }

    &.assistant {
      .message-content {
        min-width: 50%;
        max-width: 100%;
        .message-bubble {
          background-color: #fff;
          border-radius: 2px 10px 10px 10px;
          box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
        }
      }
    }
  }

  .avatar {
    width: 35px;
    height: 35px;
    border-radius: 50%;
    overflow: hidden;
    display: flex;
    align-items: center;
    justify-content: center;
    //阴影效果
    box-shadow: 0 0 10px 0 rgba(0, 0, 0, 0.1);
    img {
      width: 35px;
      height: 35px;
      object-fit: cover;
    }
  }

  .message-content {
    display: flex;
    flex-direction: column;
    max-width: 100%;
    margin: 0 12px;

    .sender-name {
      font-size: 13px;
      color: #999;
      margin-bottom: 4px;
      padding: 0 4px;
    }

    .message-bubble {
      padding: 12px 16px;
      font-size: 14px;
      line-height: 1.5;
      word-break: break-word;
      position: relative;

      .message-actions {
        display: flex;
        align-items: center;
        gap: 12px;
        margin-top: 8px;
        padding-top: 8px;
        border-top: 1px solid #f0f0f0;
        opacity: 1;
        transition: opacity 0.2s;

        .action-icon {
          width: 16px;
          height: 16px;
          cursor: pointer;
          color: #999;

          &:hover {
            color: #4e6ef2;
          }
        }

        .divider {
          width: 1px;
          height: 14px;
          background-color: #e0e0e0;
        }
      }
    }

    &:hover {
      .message-actions {
        opacity: 1;
      }
    }
  }
}

.chat-input-container {
  position: relative;
  padding: 10px 16px;
  border-top: 2px solid #fff;
  display: flex;
  flex-direction: column;
  background: url("@/assets/images/bg1.jpg") repeat center center;
}

.emoji-container-wrapper {
  position: fixed;
  bottom: 150px;
  left: 16px;
  z-index: 100;
}

.emoji-container {
  width: 300px;
  height: 260px;
  background-color: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.15);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.emoji-content {
  flex: 1;
  display: grid;
  grid-template-columns: repeat(8, 1fr);
  gap: 4px;
  padding: 10px;
  overflow-y: auto;
  @include custom-scrollbar;

  .emoji-item {
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 22px;
    height: 32px;
    cursor: pointer;
    border-radius: 4px;

    &:hover {
      background-color: #f0f2f5;
    }
  }
}

.emoji-tabs {
  display: flex;
  border-top: 1px solid #ebeef5;
  background-color: #f5f7fa;

  .emoji-tab {
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 8px 0;
    cursor: pointer;
    font-size: 18px;

    &.active {
      color: #409eff;
      border-top: 2px solid #409eff;
      margin-top: -2px;
      background-color: #fff;
    }

    &:hover {
      background-color: #ecf5ff;
    }
  }
}

.input-toolbar {
  display: flex;
  align-items: center;

  .toolbar-btn {
    padding: 6px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 4px;

    &:hover {
      background-color: #f5f7fa;
    }

    .emoji-icon {
      font-size: 20px;
      font-style: normal;
    }
  }

  .toolbar-placeholder {
    // 预留空间给未来的功能按钮
    width: 100px;
  }
}

.input-wrapper {
  display: flex;
  align-items: flex-end;
  gap: 12px;
  .send-button {
    background-color: #4e6ef2;
    color: white;
    border: none;
    padding: 6px 16px;
    border-radius: 10px;
    cursor: pointer;
    font-size: 14px;
    width: 80px;
    height: 50px;
    &:hover {
      background-color: darken(#4e6ef2, 10%);
    }
  }
  .cancel-button {
    background-color: rgb(228, 24, 24);
    color: white;
    border: none;
    padding: 6px 16px;
    border-radius: 10px;

    cursor: pointer;
    font-size: 14px;
    width: 80px;
    height: 50px;
    &:hover {
      background-color: darken(rgb(228, 24, 24), 10%);
    }
  }
}

.el-input {
  flex: 1;

  :deep(.el-textarea__inner) {
    border: 4px solid #dcdfe6;
    border-radius: 10px;
    padding: 10px 14px;
    min-height: 40px !important;
    max-height: 180px;
    overflow-y: auto;
    font-size: 14px;
    line-height: 1.5;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
    transition: all 0.2s;
    background-color: pink;

    &:focus {
      border-color: #409eff;
      box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
    }

    @include custom-scrollbar;

    &::-webkit-scrollbar {
      width: 4px;
    }
  }
}

.send-button {
  height: 40px;
  padding: 0 18px;
  font-size: 14px;
  border-radius: 4px;
  transition: all 0.2s;

  &:hover {
    transform: translateY(-1px);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  }

  &:active {
    transform: translateY(1px);
  }
}
</style>

